package com.business.dashboard.controller;

import com.business.dashboard.entity.User;
import com.business.dashboard.service.UserService;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 管理员前端用户管理控制器
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/frontend-users")
@Validated
public class AdminFrontendUserController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有前端用户
     */
    @GetMapping("")
    public ResultUtil<List<User>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            // 清除敏感信息
            users.forEach(user -> {
                user.setPassword(null);
                user.setSalt(null);
            });
            return ResultUtil.success("获取用户列表成功", users);
        } catch (Exception e) {
            log.error("获取用户列表失败，", e);
            return ResultUtil.error("获取用户列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取前端用户
     */
    @GetMapping("/{id}")
    public ResultUtil<User> getUserById(
                                       @PathVariable @NotNull Long id) {
        try {
            User user = userService.getUserById(id);
            if (user != null) {
                // 清除敏感信息
                user.setPassword(null);
                user.setSalt(null);
                return ResultUtil.success("获取用户信息成功", user);
            } else {
                return ResultUtil.error(404, "用户不存在");
            }
        } catch (Exception e) {
            log.error("获取用户信息失败，userId: {}", id, e);
            return ResultUtil.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 创建前端用户
     */
    @PostMapping("")
    public ResultUtil<User> createUser(@RequestBody @Valid User user) {
        try {
            User createdUser = userService.createUser(user);
            // 清除敏感信息
            createdUser.setPassword(null);
            createdUser.setSalt(null);
            return ResultUtil.success("创建用户成功", createdUser);
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return ResultUtil.error("创建用户失败：" + e.getMessage());
        }
    }

    /**
     * 更新前端用户信息
     */
    @PutMapping("/{id}")
    public ResultUtil<User> updateUser(@PathVariable @NotNull Long id,
                                      @RequestBody @Valid User user) {
        try {
            user.setId(id);
            User updatedUser = userService.updateUser(user);
            // 清除敏感信息
            updatedUser.setPassword(null);
            updatedUser.setSalt(null);
            return ResultUtil.success("更新用户信息成功", updatedUser);
        } catch (Exception e) {
            log.error("更新用户信息失败，userId: {}", id, e);
            return ResultUtil.error("更新用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 更新前端用户状态
     */
    @PutMapping("/{id}/status")
    public ResultUtil<String> updateUserStatus(
                                              @PathVariable @NotNull Long id,
                                              @RequestParam @NotNull Integer status) {
        try {
            boolean updated = userService.updateUserStatus(id, status);
            if (updated) {
                String message = status == 1 ? "启用用户成功" : "禁用用户成功";
                return ResultUtil.success(message);
            } else {
                return ResultUtil.error("更新用户状态失败");
            }
        } catch (Exception e) {
            log.error("更新用户状态失败，userId: {}, status: {}", id, status, e);
            return ResultUtil.error("更新用户状态失败：" + e.getMessage());
        }
    }

    /**
     * 删除前端用户
     */
    @DeleteMapping("/{id}")
    public ResultUtil<String> deleteUser(
                                        @PathVariable @NotNull Long id) {
        try {
            boolean deleted = userService.deleteUser(id);
            if (deleted) {
                return ResultUtil.success("删除用户成功");
            } else {
                return ResultUtil.error("删除用户失败");
            }
        } catch (Exception e) {
            log.error("删除用户失败，userId: {}", id, e);
            return ResultUtil.error("删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新用户状态
     */
    @PutMapping("/batch/status")
    public ResultUtil<String> batchUpdateStatus(
                                               @RequestParam List<Long> ids,
                                               @RequestParam Integer status) {
        try {
            boolean updated = userService.batchUpdateStatus(ids, status);
            if (updated) {
                return ResultUtil.success("批量更新状态成功");
            } else {
                return ResultUtil.error("批量更新状态失败");
            }
        } catch (Exception e) {
            log.error("批量更新用户状态失败，", e);
            return ResultUtil.error("批量更新状态失败：" + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    public ResultUtil<String> resetPassword(
                                           @PathVariable @NotNull Long id,
                                           @RequestParam(defaultValue = "123456") String newPassword) {
        try {
            boolean reset = userService.resetPassword(id, newPassword);
            if (reset) {
                return ResultUtil.success("重置密码成功，新密码：" + newPassword);
            } else {
                return ResultUtil.error("重置密码失败");
            }
        } catch (Exception e) {
            log.error("重置用户密码失败，userId: {}", id, e);
            return ResultUtil.error("重置密码失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近注册用户
     */
    @GetMapping("/recent")
    public ResultUtil<List<User>> getRecentUsers(
                                                @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<User> recentUsers = userService.getRecentUsers(limit);
            // 清除敏感信息
            recentUsers.forEach(user -> {
                user.setPassword(null);
                user.setSalt(null);
            });
            return ResultUtil.success("获取最近用户成功", recentUsers);
        } catch (Exception e) {
            log.error("获取最近用户失败，", e);
            return ResultUtil.error("获取最近用户失败：" + e.getMessage());
        }
    }

    /**
     * 搜索用户
     */
    @GetMapping("/search")
    public ResultUtil<List<User>> searchUsers(
                                             @RequestParam String keyword,
                                             @RequestParam(defaultValue = "1") Integer page,
                                             @RequestParam(defaultValue = "20") Integer size) {
        try {
            List<User> users = userService.searchUsers(keyword, page, size);
            // 清除敏感信息
            users.forEach(user -> {
                user.setPassword(null);
                user.setSalt(null);
            });
            return ResultUtil.success("搜索用户成功", users);
        } catch (Exception e) {
            log.error("搜索用户失败，keyword: {}", keyword, e);
            return ResultUtil.error("搜索用户失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户统计数据
     */
    @GetMapping("/stats")
    public ResultUtil<Object> getUserStats() {
        try {
            Object stats = userService.getUserStats();
            return ResultUtil.success("获取用户统计成功", stats);
        } catch (Exception e) {
            log.error("获取用户统计失败，", e);
            return ResultUtil.error("获取用户统计失败：" + e.getMessage());
        }
    }

    /**
     * 导出用户数据
     */
    @GetMapping("/export")
    public ResultUtil<Object> exportUsers(
                                         @RequestParam(defaultValue = "excel") String format) {
        try {
            // TODO: 实现用户数据导出功能
            String downloadUrl = userService.exportUsers(format);
            return ResultUtil.success("导出用户数据成功", downloadUrl);
        } catch (Exception e) {
            log.error("导出用户数据失败，", e);
            return ResultUtil.error("导出用户数据失败：" + e.getMessage());
        }
    }
}